package org.dromara.module.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.ResponseCode;
import org.dromara.common.core.utils.GsonResultBean;
import org.dromara.common.core.utils.Tools;
import org.dromara.module.domain.*;
import org.dromara.module.service.*;
import org.dromara.module.wxpay.WxAppPay;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  订单相关接口
 *@Date 2018-05-10
 */
@SaIgnore
@Slf4j
@RestController
@RequestMapping("/api/product/order")
public class ProductOrderApiController{

    @Resource
    private IProductOrderService productOrderService;
    @Resource
    private IWxUserService userService;
    @Resource
    private IAdBannerService adBannerService;
    @Resource
    private IProductService productService;
    @Resource
    private IProductAttrValueService productAttrValueService;


    @Value("${ruoyi.imgUrl}")
    private String imgPrefix;//图片地址
    @Value("${ruoyi.profile}")
    private String uploadPath;//图片地址


    /** 通过购物车生成订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject test(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/addOrder 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
//            2795
            ProductOrder order = productOrderService.getById(order_id);
            if(order!=null){
//                productOrderService.testPrint(order);
//                productOrderService.buyDeviceUpdate(order);
//                ProductOrderInfo orderInfo = productOrderInfoService.getById(195);
//                productOrderService.splitMoneyByInfo(order, orderInfo);
            }

//            MallGroupOpenList openList = mallGroupOpenListService.getById(16);
////
////            mallGroupOpenListService.refundOpenList(openList);
////            ProductOrder order, MallGroupProduct groupProduct, MallGroupOpenList openList
//            User user = userService.getById(1);
//            MallGroupProduct groupProduct = groupProductService.getById(1);
//            wxTemplateService.sendWxSubMsgOpenGroupSuccess(user,order,groupProduct,openList);
//

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取所有订单列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject getList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 1;
            int order_type = jsonRequest.containsKey("order_type") ? jsonRequest.getInt("order_type") : 0;
            // 0 - 普通用户查看列表  1 - 管理员 查看列表
            int from_type = jsonRequest.containsKey("from_type") ? jsonRequest.getInt("from_type") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户信息不存在"),true,true);
            }

            //订单状态 0 - 未支付  1 - 支付中  2 - 已支付 3 - 待发货  4 - 已发货 待收货  5 - 已完成收货待评价 6 - 已评价（已完成）
            List<ProductOrder> list = productOrderService.queryListByUserId(user_id,order_type,state,pageIndex,pageSize);

            //广告的类型  1 - 个人中心处广告  2 - 订单列表处广告 3 - 优惠券列表处广告
            AdBanner banner = adBannerService.getBannerByAdType(2);
            map.put("orders",list);
            map.put("banner",banner);
            if(banner != null){
                map.put("hasBanner",1);
            }else{
                map.put("hasBanner",0);
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.getOrderDetail(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else{
                if(order.getUserId() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
                }
            }
            map.put("order",order);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 商品的立即购买
     * @param
     * @throws Exception
     */
    @PostMapping(value="/addOrderBuyNow")
    public JSONObject addOrderBuyNow(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/addOrderBuyNow 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int count = jsonRequest.containsKey("count") ? jsonRequest.getInt("count") : 0;
            int attr_value_id = jsonRequest.containsKey("attr_value_id") ? jsonRequest.getInt("attr_value_id") : 0;
            //订单类型  0 - 平台商品类  1 - 设备上的商品类  2 - 线下商家活动  3 - 商家优惠券 4 - 团购类
            int order_type = jsonRequest.containsKey("order_type") ? jsonRequest.getInt("order_type") : 0;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductAttrValue attrValue = productAttrValueService.getById(attr_value_id);
            if(attrValue != null){
                Product product = productService.getProductInfoById(attrValue.getProductId());
                if (product != null) {
                    if(product.getIsSaleOut() == 1){
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该商品已售罄"), true, true);
                    }
                    try {
                        long order_id = productOrderService.buyNow(user, order_type, count, attrValue,remark,platform);
                        if (order_id > 0) {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "成功", order_id), true, false);
                        } else {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
                        }
                    } catch (Exception ex) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
                    }
                } else {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该商品不存在"), true, true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该商品规格不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 取消订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/cancelOrder")
    public JSONObject cancelOrder(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/cancelOrder 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.getById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
            // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
            if(order.getStatus() == 0 || order.getStatus() == 1){
                productOrderService.updateOrderState(order,5);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"订单取消成功"),true,true);
            }else if(order.getStatus() == 6){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能取消"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     *  退货申请
     * @param
     * @throws Exception
     */
    @PostMapping(value="/refundReg")
    public JSONObject refundReg(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/refundReg 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
            String reason = jsonRequest.containsKey("reason") ? jsonRequest.getStr("reason") : "";

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价
            // 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.getById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
            // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
            if(order.getStatus() == 2){
                //refund_reason_wap_explain
                order.setRefundReasonWapExplain(reason);//退货理由说明
                productOrderService.updateOrderState(order,6);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"退款申请成功"),true,true);
            }else if(order.getStatus() == 6){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已发起退款"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能退款"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     * 订单支付详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail/pay")
    public JSONObject detailPay(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/detail/pay 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            ProductOrder order = productOrderService.getById(order_id);
            if(order==null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
            map.put("allprice",order.getPayPrice());
            map.put("order_id",order_id);
            map.put("order_type",order.getOrderType());
            map.put("order_state",order.getStatus());
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取的支付参数
     * @param
     * @throws Exception
     */
    @PostMapping(value="/payInfo")
    public JSONObject payInfo(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/payInfo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getLong("order_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.getById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
            if(order.getStatus() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已支付!"),true,true);
            }else if(order.getStatus() > 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不能支付"),true,true);
            }


            WxAppPay wxAppPay = null;//new WxAppPay();
            String wxpayinfo = wxAppPay.weiXinPrePay(order.getOrderNo(),order.getPayPrice(),"购买商品",request.getRemoteAddr(),user.getOpenId(),"NORMAL");
            JSONObject jsonObject = JSONUtil.parseObj(wxpayinfo);
            map.put("wxpayinfo",jsonObject);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",wxpayinfo),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 确认收货
     * @param
     * @throws Exception
     */
    @PostMapping(value="/confirmReceipt")
    public JSONObject confirmReceipt(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("product/order/confirmReceipt 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.getById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            if(order.getStatus() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单未支付!"),true,true);
            }else if(order.getStatus() == 1){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单未发货"),true,true);
            }else if(order.getStatus() == 2){
                //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                productOrderService.updateOrderState(order,3);
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,true);
                //todo  需发送公众号推送消息  确认收货的消息
            }else if(order.getStatus() == 3){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已确认收货"),true,true);
            }else if(order.getStatus() == 4){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else if(order.getStatus() == 5){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已取消"),true,true);
            }else if(order.getStatus() == 6){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单已申请退货"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单无需确认收货"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println("" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
